package com.huilian.tool.common.utils;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;
/**
 * @author 少凡
 * date 2022/5/27 11:58
 * version 1.0
 *
 */
public class HuiLianHttpUtil {


    public static String buildUrl(String url, Map<String, Object> params) {

        StringBuilder urlBuiler = new StringBuilder(url);
        if (!url.contains("?")) {
            urlBuiler.append("?");
        }
        if (!CollectionUtils.isEmpty(params)) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                urlBuiler.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }

        url = urlBuiler.toString();
        if (url.endsWith("&")) {
            url = url.substring(0,url.length() - 1);
        }
        return url;
    }


    public static String streamToString(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();

    }

    public static String httpPostJson(String url, Map<String, String> headers, Object body) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }

        // 设置请求体
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = objectMapper.writeValueAsString(body);
        StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);

        // 发送请求并获取响应
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
            }
        }

        return null;
    }
    public static String httpPostMap(String url, Map<String, String> param) throws IOException {
        Form form = Form.form();
        for(Map.Entry<String, String> entry : param.entrySet()){
            form.add(entry.getKey(), entry.getValue());
        }

        String respString = Request.Post(url)
                .bodyForm(form.build(), Charset.forName("UTF-8"))
                .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded","UTF-8")
                        .toString()).execute().returnContent().asString();
        return respString;
    }

    public static String httpGetJson(String url) throws IOException {
        String respString = Request.Get(url).execute().returnContent().asString();
        return respString;
    }

}
